package com.itheima.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.itheima.domain.Area;
import com.itheima.service.AreaService;
import com.itheima.utils.PinYin4jUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
@Controller
public class AreaAction extends ActionSupport implements ModelDriven<Area>{

	private Area area = new Area();
	
	@Override
	public Area getModel() {
		return area;
	}
	@Autowired
	private AreaService areaService;
	
	//接收文件上传对象
	private File file;

	public void setFile(File file) {
		this.file = file;
	}
	@Action(value="area_batchImport")
	public String areaImport() throws Exception{
		System.out.println(file);
		List<Area> areas = new ArrayList<Area>();
		//编写解析代码逻辑,基于xls格式解析HSSF
		//加载excel文件对象
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		//读取一个sheet
		HSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);
		//System.out.println(sheetAt);
		//读取一个row
		//遍历这一列中的每一行
		for (Row row : sheetAt) {
			//一行数据就对应一个area对象
			//第一行是表头  跳过
			if(row.getRowNum()==0){
				continue;
			}
			if(row.getCell(0)==null || StringUtils.isBlank(row.getCell(0).getStringCellValue())){
				//是空行跳过
				continue;
			}
			//添加每一个area对象
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			
			/*//调用pinying的工具
			String province = area.getProvince();
			String city = area.getCity();
			String district = area.getDistrict();
			province = province.substring(0,province.length()-1);
			city = city.substring(0,city.length()-1);
			district = district.substring(0,district.length()-1);
			String[] headArray = PinYin4jUtils.getHeadByString(province+city+district);
			System.out.println("=======================77777777============================");
			StringBuffer buffer = new StringBuffer();
			//便利
			for (String string : headArray) {
				buffer.append(string);
			}
			//编码
			String shortCode = buffer.toString();
			area.setShortcode(shortCode);
			//城市简码
			String cityCode = PinYin4jUtils.hanziToPinyin(city,"");
			area.setCitycode(cityCode);*/
			
			areas.add(area);
		}
		//调用业务层
		areaService.saveArea(areas);
		return NONE;
	}
	private int page;
	private int rows;
	
	
	public void setPage(int page) {
		this.page = page;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	@Action(value="area_search",results={@Result(name="success",type="json")})
	public String areaSearch(){
		System.out.println("-------------------------------------------------0000");
		//接收页面过来的参数,
		Pageable pageable = new PageRequest(page-1, rows);
		Specification<Area> specification = new Specification<Area>() {
			
			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> areas = new ArrayList<Predicate>();
				if(StringUtils.isNotBlank(area.getProvince())){
					Predicate p1 = cb.like(root.get("province").as(String.class),
							"%"+area.getProvince()+"%");
					areas.add(p1);
				}
				if(StringUtils.isNotBlank(area.getCity())){
					Predicate p2 = cb.like(root.get("city").as(String.class),
							"%"+area.getCity()+"%");
					areas.add(p2);
				}
				if(StringUtils.isNotBlank(area.getDistrict())){
					Predicate p3 = cb.like(root.get("district").as(String.class),
							"%"+area.getDistrict()+"%");
					areas.add(p3);
				}
				return cb.and(areas.toArray(new Predicate[0]));
			}
		};
		//调用业务层
		Page<Area> page = areaService.findPageData(specification,pageable);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("total", page.getTotalElements());
		result.put("rows", page.getContent());
		//压值栈
		ActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}
}
